﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Development.Network.Tcp;

namespace Development.Network
{
    /// <summary>
    /// session base
    /// </summary>
    public class SessionBase
    {
        protected TcpToken m_token = null;
        public TcpToken UserToken { get { return m_token; } }
        protected readonly object _flaglock = new object();
        protected bool _isOnline;
        protected DateTime _leaveTime;
        public bool IsOnLine { get { lock (_flaglock) { return _isOnline; } } }
        public DateTime LeaveTime { get { lock (_flaglock) { return _leaveTime; } } }
        public SessionBase(TcpToken token)
        {
            m_token = token;
            m_token.EventClose += OnClose;
            _isOnline = true;
        }

        public SessionBase()
        { }

        protected virtual void OnClose(object sender)
        {
            lock (_flaglock)
            {
                m_token.EventClose -= OnClose;
                m_token = null;
                _isOnline = false;
                _leaveTime = DateTime.Now;
            }
        }

        public virtual void Close()
        {
            lock (_flaglock)
            {
                _isOnline = false;
                _leaveTime = DateTime.Now;
                if (m_token != null)
                {
                    m_token.EventClose  -= OnClose;
                    m_token.Close();
                    m_token = null;
                }
            }
        }

        public void SendMsg(byte [] msg)
        {
            if(m_token != null && IsOnLine)
            {
                m_token.Send(msg);
            }
        }

        public void SetToken(TcpToken token)
        {
            lock (_flaglock)
            {
                _isOnline = true;
                if (!token.Equals(m_token))
                {
                    if (m_token != null)
                    {
                        m_token.EventClose -= OnClose;
                        m_token.Close();
                        m_token = null;
                    }
                    m_token = token;
                    m_token.EventClose += OnClose;
                }
            }
        }

    }
}
